/**
 *
 */
package com.block.common.security.service.sign;

import com.alibaba.fastjson.JSONObject;
import com.block.common.security.service.AppSignMannerService;
import com.block.common.security.service.factory.SignFactory;
import com.block.common.util.HmacHanlder;
import com.block.db.entity.AppEncrypt;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Map;


/**
 * 
 * 【外部接口专用】
 * 第三版签名加密方式
 */
public class ThirdVersionSignEncryptService extends AppSignMannerService {
//	private static final Logger log = Logger.getLogger(ThirdVersionSignEncryptService.class);

	/**
	 * 签名
	 * @param appEncrypt
	 * @param tranData
	 * @return
	 * 2016年10月12日 上午10:42:57
	 */
	@Override
	public String sign(AppEncrypt appEncrypt, String tranData, String randomKey) {
		boolean isSign = appEncrypt.getIsSign().equals(SignFactory.IS_SIGN);
		if (isSign)
		{
			try {
				HmacHanlder hmacHanlder = new HmacHanlder(randomKey);
				return URLEncoder.encode(hmacHanlder.encrypt(tranData), "utf-8");
			} catch (Exception e) {
//				log.error("【签名数据出现异常】【randomKey】" + randomKey + "【tranData】" + tranData, e);
				e.printStackTrace();
				return null;
			}
		}
		return tranData;
	}

	/**
	 * 验签
	 * @param appEncrypt
	 * @param ciphertext
	 * @param reqSignStr
	 * @param tranData
	 * @return
	 * 2016年12月19日 下午5:51:46
	 */
	@Override
	public boolean validateSign(AppEncrypt appEncrypt, String reqSignStr, Map<String, Object> reqMap, String ciphertext, JSONObject tranData) {
		boolean isSign = appEncrypt.getIsSign().equals(SignFactory.IS_SIGN);
		if (isSign)
		{
			String rsaKeyDecoded = reqMap.get("rsaKeyDecoded").toString();
			try {
				HmacHanlder hmacHanlder = new HmacHanlder(rsaKeyDecoded);
				//签名
				String signFinal = hmacHanlder.encrypt(reqMap.get("tranDataDecoded").toString());
				return URLDecoder.decode(reqSignStr, "utf-8").equals(signFinal);
			} catch (Exception e) {
//				log.error("【验签出现异常】【rsaKey】" + rsaKeyDecoded + "【reqSignStr】" + reqSignStr, e);
				e.printStackTrace();
				return false;
			}
		}
		return true;
	}



}
